package com.javatiaocao.myblog.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javatiaocao.myblog.constant.CodeType;
import com.javatiaocao.myblog.mapper.ArticleMapper;
import com.javatiaocao.myblog.mapper.CategoryMapper;
import com.javatiaocao.myblog.model.Article;
import com.javatiaocao.myblog.model.Categories;
import com.javatiaocao.myblog.service.CategoryService;
import com.javatiaocao.myblog.utils.DataMap;
import com.javatiaocao.myblog.utils.StringAndArray;
import com.javatiaocao.myblog.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    CategoryMapper categoryMapper;


    @Override
    public DataMap getCategoriesList() {
        //查询分类表
        List<Categories> categoryServiceList = articleMapper.selectCategoriesList();
        //判断是否为空
        if (categoryServiceList.isEmpty()){
            return DataMap.fail(CodeType.SERVER_EXCEPTION);
        }

        JSONObject returnJson = new JSONObject();
        JSONArray jsonArray= new JSONArray();
        for (Categories categories : categoryServiceList) {
            //创建Json对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",categories.getId());
            jsonObject.put("categoryName",categories.getCategoryName());
            //放入数组
            jsonArray.add(jsonObject);
        }
        returnJson.put("result",jsonArray);

        return DataMap.success().setData(returnJson);
    }

    @Override
    public DataMap addCategory(Categories categories, Integer type) {
        Categories copyCategories = articleMapper.selectCategoriesByName(categories.getCategoryName());
        int existCategoryArticle = articleMapper.findArticleByCAtegory(categories.getCategoryName());
        if (type.equals(1)) {
            //查询是否存在分类
            if (copyCategories != null) {
                return DataMap.fail(CodeType.CATEGORY_EXIST);
            } else if (categories.getCategoryName() == null) {
                return DataMap.fail(CodeType.COMMENT_BLANK);
            }
            //不存在则创建
            articleMapper.createCategories(categories.getCategoryName());
            return DataMap.success(CodeType.ADD_CATEGORY_SUCCESS).setData(
                    articleMapper.selectCategoriesByName(categories.getCategoryName()));
        } else if (type.equals(2)) {
            //删除模块
            if (existCategoryArticle != 0){
                //分类下存在文章
                return DataMap.fail(CodeType.CATEGORY_HAS_ARTICLE);
            }
            if (copyCategories == null) {
                //分类不存在
                return DataMap.fail(CodeType.CATEGORY_NOT_EXIST);
            }
            articleMapper.deleteCategories(categories.getCategoryName());
            return DataMap.success(CodeType.DELETE_CATEGORY_SUCCESS);
        }

        return DataMap.fail();
    }


    //下拉列表
    @Override
    public DataMap findCategoriesName() {
        //查询所有分类对象
        List<Categories> categoriesList = articleMapper.selectCategoriesList();
        if (categoriesList.isEmpty()){
            return DataMap.fail(CodeType.SERVER_EXCEPTION);
        }
        JSONArray jsonArray = new JSONArray();
        for (Categories categories : categoriesList) {
            jsonArray.add(categories.getCategoryName());
        }
        return DataMap.success().setData(jsonArray);
    }

    @Override
    public DataMap findCategoriesNameAndNum() {

        List<Categories> categoriesList = categoryMapper.selectCategoriesList();
        if (StringUtil.BLANK.equals(categoriesList) || categoriesList == null){
            return DataMap.fail(CodeType.COMMENT_BLANK);
        }

        JSONArray categoryNameAndArticleNum = new JSONArray();
        for (Categories categories : categoriesList) {
            JSONObject categoryNameAndArticleJsonObject = new JSONObject();
            int categoryArticleNum = articleMapper.selectArticleNumByCategory(categories.getCategoryName());
            categoryNameAndArticleJsonObject.put("categoryArticleNum",categoryArticleNum);
            categoryNameAndArticleJsonObject.put("categoryName",categories.getCategoryName());
            categoryNameAndArticleNum.add(categoryNameAndArticleJsonObject);
        }

        //返回数据处理
        JSONObject returnObject = new JSONObject();
        returnObject.put("result",categoryNameAndArticleNum);

        return DataMap.success().setData(returnObject);
    }

    /**
     *
     * 根据目录获得文章
     * @param rows
     * @param pageNum
     * @param category
     * @return
     */
    @Override
    public DataMap getCategoryArticle(Integer rows, Integer pageNum, String category) {
        //数据封装
        HashMap<String, Object> returnHashMap = new HashMap<>();
        PageHelper.startPage(pageNum, rows);

        List<Article> articleList;

        //获取文章
        if (StringUtil.BLANK.equals(category) || category == null){
            category = "全部文章";
            articleList = articleMapper.selectArticleWithPage();
        }else {
            articleList = articleMapper.getCategoryArticle(category);
        }
        if (articleList == null){//可能存在目录下没有文章的情况
            return DataMap.success(CodeType.ARTICLE_NOT_EXIST);
        }

        //  rows: data['data']['pageInfo']['pageSize'],//每页显示条数
        //                    pageNum: data['data']['pageInfo']['pageNum'],//当前所在页码
        //                    pages: data['data']['pageInfo']['pages'],//总页数
        //                    total: data['data']['pageInfo']['total'],//总记录数
        PageInfo<Article> pageInfo = new PageInfo<>(articleList);
        HashMap<String, Object> pageInfoHashMap = new HashMap<>();
        pageInfoHashMap.put("pageNum", pageInfo.getPageNum());
        pageInfoHashMap.put("pages", pageInfo.getPages());
        pageInfoHashMap.put("total", pageInfo.getTotal());
        pageInfoHashMap.put("pageInfo", pageInfo);
        returnHashMap.put("pageInfo", pageInfoHashMap);

        //data['category']
        returnHashMap.put("category",category);
        //articleId,articleTitle,publishDate,articleCategories,articleTags.length
        //data['result'], function (index, obj)
        ArrayList<HashMap> articleMapList = new ArrayList<>();
        for (Article article : articleList) {
            HashMap<String, Object> object = new HashMap<>();
            object.put("articleId", article.getArticleId());
            object.put("articleTitle", article.getArticleTitle());
            object.put("publishDate", article.getPublishDate());
            object.put("articleCategories", article.getArticleCategories());
            String[] tags = StringAndArray.stringToArray(article.getArticleTags());
            object.put("articleTags", tags);
            articleMapList.add(object);
        }
        returnHashMap.put("result", articleMapList);

        return DataMap.success().setData(returnHashMap);
    }


}
